import * as Api from '@/api/system/dict'
import dictConsts from '@/utils/dict-consts'

const dict = {
  state: {
    dictObj: {}
  },
  getters: {
    getDictCacheListByType: (state) => (typeCode) => {
      return typeCode ? state.dictObj[typeCode] : ''
    }
  },
  mutations: {
    setDictObj (state, dictObj) {
      state.dictObj = dictObj
    }
  },
  actions: {
    CacheDict({ commit }) {
      return new Promise((resolve, reject) => {
        Api.getDictCache(Object.values(dictConsts))
          .then(res => {
            commit('setDictObj', res.data)
            resolve()
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    GetDictPage({ commit }, { typeCode, param }) {
      return new Promise((resolve, reject) => {
        Api.getDictPage(typeCode, param)
          .then(res => {
            resolve(res.data)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    SaveDict({ commit }, { typeCode, data }) {
      return new Promise((resolve, reject) => {
        Api.saveDict(typeCode, data)
          .then(res => {
            resolve(res.data)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    GetDictById({ commit }, { typeCode, code }) {
      return new Promise((resolve, reject) => {
        Api.getDictById(typeCode, code)
          .then(res => {
            resolve(res.data)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    UpdateDictById({ commit }, { typeCode, code, data }) {
      return new Promise((resolve, reject) => {
        Api.updateDictById(typeCode, code, data)
          .then(res => {
            resolve(res.data)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    RemoveDictById({ commit }, { typeCode, code }) {
      return new Promise((resolve, reject) => {
        Api.removeDictById(typeCode, code)
          .then(res => {
            resolve(res.data)
          })
          .catch(err => {
            reject(err)
          })
      })
    }
  }
}

export default dict
